var DBFactory = require('../db/mysql_db');
var addresstDao = module.exports;

function setDefaultAddress(data, cb) {
    var sql = 'update shop_receive_addr set is_default = ? where uid = ? ';
    DBFactory.poolQuery(sql, [0, data.uid],
        function(){
            cb('no collection');
        },function (err,result) {
            if(err){
                cb(err);
                console.log('update_default Err: ' + err);
                return;
            }
            saveAddress(data, cb);
        }
    );
}

function saveAddress(data, cb) {
    var sql = 'replace into shop_receive_addr set ? ';
    DBFactory.poolQuery(sql, data,
        function(){
            cb('no collection');
        },function (err,result) {
            if(err){
                cb(err);
                console.log('saveAddress Err: ' + err);
                return;
            }
            cb(null, '编辑或添加类别成功！');
        }
    );
}

addresstDao.save = function(data, cb) {
    if(!data) return cb(new ERR(500));
    if(parseInt(data.is_default) == 1) {
        setDefaultAddress(data, cb);
    } else {
        saveAddress(data, cb);
    }
}

addresstDao.list = function(data, cb) {
    if(!data) return cb(new ERR(500));
    var sql = 'select * from shop_receive_addr where uid = ? limit ?, ? ';
    DBFactory.poolQuery(sql, [data.uid, data.start, data.size],
        function(){
            cb('no collection');
        },function (err,result) {
            if(err){
                cb(err);
                console.log('list Err: ' + err);
                return;
            }
            cb(null, result);
        }
    );
}

addresstDao.delete = function(data, cb) {
    if(!data) return cb(new ERR(500));
    var sql = 'delete from shop_receive_addr where uid = ?  and id = ? ';
    DBFactory.poolQuery(sql, [data.uid, data.id],
        function(){
            cb('no collection');
        },function (err,result) {
            if(err){
                cb(err);
                console.log('list Err: ' + err);
                return;
            }
            cb(null, '移除地址成功！');
        }
    );
}